import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../TabBar/TabbarView.dart';
import '../../http/api.dart';

class CancelWaybillList extends StatefulWidget {
  const CancelWaybillList({super.key, required this.waybillId, required this.deposit});
  final String waybillId;
  final String deposit;
  @override
  State<CancelWaybillList> createState() => _CancelWaybillListState();
}

class _CancelWaybillListState extends State<CancelWaybillList> {
  int isDespoit=1;
  List shipperReason=["临时不需要用车了","从其他途径出发","货物信息填写错误","禁区限行（未和司机沟通）","天气原因"];
  List driverReason=["司机迟到、爽约","司机车辆与要求不符","要求加价或线下交易","无任何理由不装货物","禁区限行（已和司机沟通）"];
  List driverReasonID=["1742427987141242881","1743163761641943042","1743163890398687233","1743163966546276354","1743164073236787202"];
  List shipperReasonID=["1743164884008333313","1743164484660260866","1743164528109056002","1743164611009474561","1743164427445760002"];
  int isChooseShipper=0;
  int isChooseDriver=0;
  int checkShipperIndex=-1;
  int checkDriverIndex=-1;


  Future<void> cancelAction(String cancelType,String cancelMessageId,String cancelMessage) async {
    print(widget.waybillId);
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/waybill/waybill/common/cancelWaybill',
      data: {
        "waybillId":widget.waybillId,
        "cancelStatus":0,
        "depositType":isDespoit,
        "cancelType": cancelType,
        "cancelMessageId": cancelMessageId,
        "cancelMessage": cancelMessage
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          BrnToast.show("操作成功", context);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
          ); // 点击返回箭头时返回到

        } else {
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title:Text( "取消运单",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(left: 12.w, top: 16.h,bottom: 17.h,right: 12.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("订金金额",style: TextStyle(color: Colors.black),),
                        Text("¥"+widget.deposit,style: TextStyle(color: Colors.black),),
                      ],
                    ),
                    SizedBox(height: 22.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("退还订金",style: TextStyle(color: Colors.black),),
                       GestureDetector(
                         child: Icon(isDespoit==1? Icons.circle_outlined : Icons.check_circle,color:isDespoit==1? MyColors.textColor:MyColors.themeColor,),
                         onTap: (){
                           setState(() {
                             isDespoit==0?isDespoit=1:isDespoit=0;
                           });
                         },
                       ),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 22.w,top: 10.h,bottom: 10.h),
                child: Row(
                  children: [
                    Text("请选择取消原因",style: TextStyle(color: Colors.black),),
                    Text("（必选）",style: TextStyle(color: MyColors.themeColor),),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(left: 10.w, top: 9.h,bottom: 8.h,right: 13.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset("lib/Images/OrderList/取消运单货主icon.png",width: 20.w,height: 20.h,),
                        SizedBox(width: 13.w,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("发货原因",style: TextStyle(color: Colors.black),),
                            Text("发货原因导致订单取消，请谨慎操作",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                          ],
                        )
                      ],
                    ),
                    GestureDetector(
                      child: Icon(isChooseShipper==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.authTipColor,size: 30,),
                      onTap: (){
                        setState(() {
                          isChooseShipper==0?isChooseShipper=1:isChooseShipper=0;
                        });
                      },
                    ),
                  ],
                ),
                ),
              if(isChooseShipper==1)
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w),
                padding: EdgeInsets.only(left: 23.w, top: 16.h,bottom: 18.h,right: 11.w),
                height: 200.h,
                decoration: BoxDecoration(
                    color: Color.fromRGBO(240, 240, 240, 1),
                    borderRadius: BorderRadius.only( bottomRight: Radius.circular(10),bottomLeft: Radius.circular(10))),
                child:  ListView.builder(
                    itemCount:shipperReason.length ,
                    itemBuilder: (context, index) {
                      return Container(
                        padding: EdgeInsets.only(top: 8.h,bottom: 8.h),
                        child:  Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(shipperReason[index],style: TextStyle(color: MyColors.textColor),),
                            GestureDetector(
                              child: Icon(  checkShipperIndex==index?Icons.check_circle: Icons.circle_outlined,color:checkShipperIndex==index?MyColors.themeColor: MyColors.authTipColor,size: 25,),
                              onTap: (){
                                  setState(() {
                                    checkDriverIndex=-1;
                                    if(checkShipperIndex==index)
                                      checkShipperIndex=-1;
                                    else
                                    checkShipperIndex=index;
                                  });
                              },
                            ),
                          ],
                        ) ,
                      )
                      ;}),

              ),
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(left: 10.w, top: 9.h,bottom: 8.h,right: 13.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset("lib/Images/OrderList/取消运单司机icon.png",width: 20.w,height: 20.h,),
                        SizedBox(width: 13.w,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("司机原因",style: TextStyle(color: Colors.black),),
                            Text("司机原因导致订单取消，请谨慎操作",style: TextStyle(color: MyColors.authTipColor,fontSize: 12.sp),),
                          ],
                        )
                      ],
                    ),
                    GestureDetector(
                      child: Icon(isChooseDriver==0?Icons.keyboard_arrow_down:Icons.keyboard_arrow_up,color: MyColors.authTipColor,size: 30,),
                      onTap: (){
                        setState(() {
                          isChooseDriver==0?isChooseDriver=1:isChooseDriver=0;
                        });
                      },
                    ),
                  ],
                ),
              ),
              if(isChooseDriver==1)
                Container(
                  margin: EdgeInsets.only(left: 10.w,right: 10.w),
                  padding: EdgeInsets.only(left: 23.w, top: 16.h,bottom: 18.h,right: 11.w),
                  height: 200.h,
                  decoration: BoxDecoration(
                      color: Color.fromRGBO(240, 240, 240, 1),
                      borderRadius: BorderRadius.only( bottomRight: Radius.circular(10),bottomLeft: Radius.circular(10))),
                  child:  ListView.builder(
                      itemCount:driverReason.length ,
                      itemBuilder: (context, index) {
                        return Container(
                          padding: EdgeInsets.only(top: 8.h,bottom: 8.h),
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(driverReason[index],style: TextStyle(color: MyColors.textColor),),
                              GestureDetector(
                                child: Icon(  checkDriverIndex==index?Icons.check_circle: Icons.circle_outlined,color:checkDriverIndex==index?MyColors.themeColor: MyColors.authTipColor,size: 25,),
                                onTap: (){
                                  setState(() {
                                    checkShipperIndex=-1;
                                    if(checkDriverIndex==index)
                                      checkDriverIndex=-1;
                                      else
                                    checkDriverIndex=index;
                                  });
                                },
                              ),
                            ],
                          ) ,
                        )
                        ;}),

                ),
            ],
          ),
          ),
          Container(
            height: 85.h,
            color: Colors.white,
            padding: EdgeInsets.only(top: 10.h,right: 15.w,left: 15.w,bottom: 40.h),
            child: BrnSmallMainButton(
              title: "提交",
              width: screenSize.width-30.w,
              bgColor: MyColors.themeColor,
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              radius: 30,
              onTap: () {
                  if(checkShipperIndex!=-1)
                    cancelAction("0",shipperReasonID[checkShipperIndex],shipperReason[checkShipperIndex]);
                  else
                    cancelAction("1",driverReasonID[checkDriverIndex],driverReason[checkDriverIndex]);
              },
            ),
          )
        ],
      ),
    );
  }
}
